package service

import (
	"errors"

	"github.com/jiedan/student-web/server/model"
	"gorm.io/gorm"
)

// TeacherService 教师服务
type TeacherService struct {
	DB *gorm.DB
}

// NewTeacherService 创建教师服务
func NewTeacherService(db *gorm.DB) *TeacherService {
	return &TeacherService{DB: db}
}

// CreateTeacher 创建教师记录
func (s *TeacherService) CreateTeacher(userID uint, department, title, description string) (*model.Teacher, error) {
	// 检查用户是否存在
	var user model.User
	result := s.DB.First(&user, userID)
	if result.Error != nil {
		return nil, errors.New("user not found")
	}

	// 检查用户角色是否为教师
	var role model.Role
	result = s.DB.First(&role, user.RoleID)
	if result.Error != nil || role.Name != "teacher" {
		return nil, errors.New("user is not a teacher role")
	}

	// 检查用户是否已经是教师
	var existingTeacher model.Teacher
	result = s.DB.Where("user_id = ?", userID).First(&existingTeacher)
	if result.Error == nil {
		return nil, errors.New("user is already a teacher")
	}

	// 创建教师记录
	teacher := model.Teacher{
		UserID:      userID,
		Department:  department,
		Title:       title,
		Description: description,
	}

	result = s.DB.Create(&teacher)
	if result.Error != nil {
		return nil, errors.New("failed to create teacher record")
	}

	return &teacher, nil
}